package com.atguigu.tingshu.order.factory;

import com.atguigu.tingshu.order.service.OrderInfoService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author GQS @Date 2024/11/11/9:16 @Description
 * 策略模式的工厂对象的实现类
 */
@Service
public class TingshuFactoryImpl implements TingshuFactory, ApplicationContextAware {

  //私有的全局变量,存储不同类型的订单的不同实现类: key=itemType value=bean的实现类
  // 单例bean有成员属性的话 要考虑线程安全
  private Map<String, OrderInfoService> orderInfoServiceMap= new ConcurrentHashMap<>();
  /**
   * 根据类型匹配 返回指定的bean
   * @param itemType
   * @return
   */
  @Override
  public OrderInfoService getOrderInfoService(String itemType) {
    return orderInfoServiceMap.get(itemType);
  }

  /**
   * spring自动配置结束之后 自动触发
   * @param applicationContext
   * @throws BeansException
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    // 获取指定类型的bean的map: (key=bean的名称 value=bean对象)
    Map<String, OrderInfoService> beansOfTypeMap =
        applicationContext.getBeansOfType(OrderInfoService.class);
    // 转化为一个map: key=itemType value=bean的对象
    beansOfTypeMap.entrySet()
        .forEach(
            entry -> {
              // 获取到bean的对象
              OrderInfoService orderInfoService = entry.getValue();
              // 获取到注解的值
              GuiguItemType guiguItemType = orderInfoService.getClass().getAnnotation(GuiguItemType.class);
              String itemType = guiguItemType.itemType();
              // String itemType = orderInfoService.getClass().getAnnotation(GuiguItemType.class).itemType();
              // 第二种方法 通过方法获取 弃用
              // String itemType = orderInfoService.getItemType();
              // 存储到map中
              orderInfoServiceMap.put(itemType, orderInfoService);
            });
    // System.out.println("orderInfoServiceMap = " + orderInfoServiceMap);
  }
}